import fitz  # PyMuPDF
import requests
import json
import os
#国家局上报办件关键信息从核查结果通知附件中 提取过滤
# DeepSeek API配置
DEEPSEEK_API_URL = "https://api.deepseek.com/analyze"
API_KEY = "sk-04c465ff193240629fc462e0a72abc88"

def extract_images_from_pdf(pdf_path):
    images = []
    pdf_document = fitz.open(pdf_path)
    for page_num in range(len(pdf_document)):
        page = pdf_document.load_page(page_num)
        image_list = page.get_images(full=True)
        for img_index, img in enumerate(image_list):
            xref = img[0]
            base_image = pdf_document.extract_image(xref)
            image_bytes = base_image["image"]
            image_ext = base_image["ext"]
            image_name = f"image{page_num+1}_{img_index+1}.{image_ext}"
            images.append((image_name, image_bytes))
    return images

def analyze_image_with_deepseek(image_name, image_bytes):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/octet-stream"
    }
    files = {
        "file": (image_name, image_bytes)
    }
    response = requests.post(DEEPSEEK_API_URL, headers=headers, files=files)
    print(response.text)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error analyzing image {image_name}: {response.status_code}")
        return None

def extract_specific_content_from_response(response_json):
    production_address = None
    registration_sample = None
    clinical_trial_sample = None

    # 假设DeepSeek API返回的JSON结构如下
    # 根据实际API返回的结构进行调整
    if "results" in response_json:
        for result in response_json["results"]:
            if "text" in result:
                text = result["text"].lower()
                if "生产地址" in text:
                    production_address = text.split("生产地址")[-1].strip()
                elif "注册检验样品和临床试验用样品真实性" in text:
                    registration_sample = text.split("注册检验样品和临床试验用样品真实性")[-1].strip()

    return production_address, registration_sample

def main(pdf_path):
    images = extract_images_from_pdf(pdf_path)
    for image_name, image_bytes in images:
        response_json = analyze_image_with_deepseek(image_name, image_bytes)
        if response_json:
            production_address, registration_sample = extract_specific_content_from_response(response_json)
            print(f"Image: {image_name}")
            print(f"Production Address: {production_address}")
            print(f"Registration Sample: {registration_sample}")
            print("-" * 40)

if __name__ == "__main__":
    pdf_path = "F:\\txhcFile\\0e1e4a81-76c6-4a7b-8512-f9cf2a4c8fed.pdf"  # 替换为你的PDF文件路径
    main(pdf_path)
